<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
# 添加api错误提示
use App\Exceptions\ApiException;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    
    public function getTree($data, $parent_id = 0)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v["parent_id"] == $parent_id) {
                unset($data[$k]);
                if (!empty($data)) {
                    $children = $this->getTree($data, $v["id"]);
                    if (!empty($children)) {
                        $v["children"] = $children;
                    }
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }

    public function validate(array $rules, array $messages = [], array $customAttributes = [])
    {
      $validator = $this->getValidationFactory()->make(request()->all(), $rules, $messages, $customAttributes);
      if ($validator->fails()) {
        throw new ApiException($validator->errors()->first());
      }
    }

    public function success($data=null,$msg=null)
    {
        $ret = [
            'code'  => 0,
            'msg'   => $msg,
            'data'  => $data,
        ];

        if(is_string($data) && $msg==null){
            $ret['msg'] = $data;
            $ret['data'] = null;
        }

        return response()->json($ret, 200);
    }

    public function error($msg=null,$data=null)
    {
        return response()->json(["code"=>400,"msg"=>$msg,"data"=>$data], 200);
    }

    public function succ($data=null,$msg=null)
    {
        return $this->success($data,$msg);
    }
    
}
